<template>
    <div>
        <h1>{{ msg }}</h1>
        <input v-model="userQuestion" placeholder="请输入您的问题" />
        <button @click="startAnswering">提交</button>
        <h2>思考过程:</h2>
        <p>{{ reasoningContent }}</p>
        <h2>完整回复:</h2>
        <p>{{ answerContent }}</p>
    </div>
</template>

<script>
import OpenAI from "openai";

export default {
    name: 'AI',
    props: {
        msg: String
    },
    data() {
        return {
            userQuestion: '',// 用于存储用户输入的问题
            reasoningContent: '',// 用于存储模型的思考过程
            answerContent: '',// 用于存储模型的完整回答
            isAnswering: false// 标记是否已经开始回答问题
        }
    },
    methods: {
        async startAnswering() {
            if (this.userQuestion.trim() === '') {
                alert('请输入问题');
                return;
            }

            // 清除之前的思考过程和回答内容
            this.reasoningContent = '';
            this.answerContent = '';
            this.isAnswering = false;

            try {
                // 调用大模型生成回答
                const stream = await openai.chat.completions.create({
                    model: 'qwq-32b',// 指定使用的模型
                    messages: [{ role: 'user', content: this.userQuestion }],
                    stream: true// 启用流式输出
                });

                console.log('\n' + '='.repeat(20) + '思考过程' + '='.repeat(20) + '\n');

                // 处理流式输出的每个chunk
                for await (const chunk of stream) {
                    if (!chunk.choices?.length) {
                        console.log('\nUsage:');
                        console.log(chunk.usage);
                        continue;
                    }

                    const delta = chunk.choices[0].delta;
                    console.log("delta", delta);

                    // 处理思考过程
                    if (delta.reasoning_content) {
                        this.reasoningContent += delta.reasoning_content;
                    }
                    // 处理正式回复
                    else if (delta.content) {
                        if (!this.isAnswering) {
                            console.log('\n' + '='.repeat(20) + '完整回复' + '='.repeat(20) + '\n');
                            // 标记已经开始回答问题
                            this.isAnswering = true;
                        }
                        // 更新完整回答内容
                        this.answerContent += delta.content;
                    }
                }
            } catch (error) {
                console.error('Error:', error);
            }
        }

    },
}

const openai = new OpenAI({
    apiKey: process.env.VUE_APP_DASHSCOPE_API_KEY, // 从环境变量读取
    baseURL: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
    dangerouslyAllowBrowser: true
});
</script>

<style>
@media (min-width: 1024px) {
    .about {
        min-height: 100vh;
        display: flex;
        align-items: center;
    }
}
</style>
